using System;
using System.Collections.Generic;


namespace WtfManager.Utilities
{
  public class TypeComparer : Comparer<Type>
  {
    #region Fields


    private readonly Type _dataType;


    #endregion


    #region Constructors/Finalizers


    public TypeComparer(Type dataType)
    {
      _dataType = dataType;
    }


    #endregion


    #region Methods


    public override int Compare(Type type1, Type type2)
    {
      int depth1 = GetInheritanceDepth(type1);
      int depth2 = GetInheritanceDepth(type2);

      if (depth1 == depth2)
      {
        return 0;
      }

      if (depth1 == 0)
      {
        return -1;
      }

      if (depth2 == 0)
      {
        return 1;
      }

      if (depth1 < depth2)
      {
        return -1;
      }

      return 1;
    }


    private int GetInheritanceDepth(Type type)
    {
      int counter = 0;

      while (type != null)
      {
        if (type == _dataType)
        {
          return counter;
        }

        counter++;

        type = type.BaseType;
      }

      return 0;
    }


    #endregion
  }
}